<template>
  <el-dialog v-model="dialogVisible" title="证件配置" width="80%" :before-close="handleClose">
    <div class="set-box">
      <div class="set-box-item">
        <p>人证配置</p>
        <div class="item-type">
          <span class="item-type-label">证件类型:</span>
          <el-checkbox-group v-model="selectPerson.data" @change="personChange">
            <el-checkbox v-for="item in personTypeList.data" :key="item.id" :label="item.cnName" :value="item">{{ item.cnName }}</el-checkbox>
          </el-checkbox-group>
        </div>
        <div class="item-number">
          <div class="item-number-value" v-for="(item,index) in selectData.data" :key="item.id">
            <span>{{selectData.data[index]['cnName']}}：</span>
            <el-input-number v-model="selectData.data[index]['certNum']" :min="0" />
          </div>
        </div>
      </div>
      <div class="set-box-item">
        <p>车证配置</p>
        <div class="item-type">
          <span class="item-type-label">证件类型</span>
          <el-checkbox-group v-model="selectCar.data" @change="carChange">
            <el-checkbox v-for="item in carTypeList.data" :key="item.id" :label="item.cnName" :value="item">{{ item.cnName }}</el-checkbox>
          </el-checkbox-group>
        </div>
        <div class="item-number-car">
          <div v-for="(item,index) in selectCarData.data" :key="item.id">
            <span class="item-number-label">{{selectCarData.data[index]['cnName']}}</span>
            <div class="item-number-item">
              <span>额度:</span>
              <el-input-number v-model="selectCarData.data[index]['certNum']" :min="0"/>
            </div>
            <div class="item-number-item">
              <span>停车区域:</span>
              <el-checkbox-group v-model="selectCarData.data[index]['userCertAreas']">
                <el-checkbox v-for="item in carAreaList.data" :key="item.id" :label="item.areaName" :value="item.id">{{ item.areaName }}</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref,reactive,watch,onMounted } from "vue";
import {_getAreaList, _getCardTypeList, _getCardTypeSet, _updateCardTypeSet, _updateQuota} from "../../http/api.js";
import {ElLoading, ElMessage} from "element-plus";

const $emit = defineEmits(['showEditEmit'])
const props = defineProps({
  id:String,
})

const dialogVisible = ref(true); // 弹框显示
const carAreaList = reactive({ // 停车区域列表
  data:[]
})
const personTypeList = reactive({ // 人证证件类型列表
  data:[]
})
const selectPerson = reactive({ // 人证选择的证件类型列表
  data:[]
})
const selectData = reactive({ // 人证最终数据列表
  data:[]
})
const carTypeList = reactive({ // 车证证件类型列表
  data:[]
})
const selectCar = reactive({ // 车证选择的证件类型列表
  data:[]
})
const selectCarData = reactive({ // 车证最终数据列表
  data:[]
})

//获取证件类型列表
const getCardTypeList = () => {
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'});
  _getCardTypeList(1,1000)
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok){
          let records = res.data.data.records;
          if(records.length > 0) {
            records.forEach(item => {
              if(item.typeName === '人证') {
                personTypeList.data.push(item)
              }
              if(item.typeName === '车证') {
                carTypeList.data.push(item)
              }
            })
          }
          getCardTypeSet()
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
        ElMessage.error('网络异常请重试')
      })
}
getCardTypeList();

//获取停车区域列表
const getAreaList = () => {
  _getAreaList(1,1000)
      .then(res => {
        console.log(res);
        if(res.data.ok){
          let item = res.data.data;
          carAreaList.data = item.records;
        }
      })
      .catch(err => {
        console.log(err);
      })
}
getAreaList();

//人员选择改变
const personChange = (val) => {
  let oldArr = JSON.parse(JSON.stringify(val));
  if(val.length > selectData.data.length) { // 新增
    for (let i = 0; i < selectData.data.length; i++) {
      for (let j = 0; j < oldArr.length; j++) {
        if(selectData.data[i].certId === oldArr[j].id) {
          oldArr.splice(j,1)
        }
      }
    }
    oldArr.forEach(v => {
      let params = { certId: v.id, certNum: 0,cnName:v.cnName }
      selectData.data.push(params);
    })
  }else { // 删除
    let newArr = [];
    for (let i = 0; i < oldArr.length; i++) {
      for (let j = 0; j < selectData.data.length; j++) {
        if(selectData.data[j].certId === oldArr[i].id) {
          newArr.push(selectData.data[j])
        }
      }
    }
    selectData.data = newArr
  }
}
// 车证选择改变
const carChange = (val) => {
  let oldArr = JSON.parse(JSON.stringify(val));
  if(val.length > selectCarData.data.length) { // 新增
    for (let i = 0; i < selectCarData.data.length; i++) {
      for (let j = 0; j < oldArr.length; j++) {
        if(selectCarData.data[i].certId === oldArr[j].id) {
          oldArr.splice(j,1)
        }
      }
    }
    oldArr.forEach(v => {
      let params = { certId: v.id, certNum: 0,cnName:v.cnName,userCertAreas:[] }
      selectCarData.data.push(params);
    })
  }else { // 删除
    let newArr = [];
    for (let i = 0; i < oldArr.length; i++) {
      for (let j = 0; j < selectCarData.data.length; j++) {
        if(selectCarData.data[j].certId === oldArr[i].id) {
          newArr.push(selectCarData.data[j])
        }
      }
    }
    selectCarData.data = newArr
  }
}

// 关闭弹框
const handleClose = () => {
  $emit('showEditEmit')
}
//保存
const save = () => {
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)' })
  let arrData = [... selectData.data, ... selectCarData.data];
  console.log(arrData);
  let params = [];
  arrData.forEach(v => {
    let userCertAreasList = v.userCertAreas||[];
    let arr = [];
    userCertAreasList.forEach(item => {
      arr.push({
        // userId: props.id,
        areaId: item
      })
    })
    let vs = JSON.parse(JSON.stringify(v));
    if(arr.length) {
      vs['userCertAreas'] = arr;
    }
    if(vs.certAreaVos) {
      delete vs.certAreaVos
    }
    if(vs.cnName) {
      delete vs.cnName
    }
    params.push({userId:props.id,... vs})
  })
  console.log(params);
  _updateQuota(props.id,params)
      .then(res => {
        loading.close();
        if(res.data.ok) {
          ElMessage({ message: '更新成功', type: 'success'});
          $emit('showEditEmit')
        }
      })
      .catch(err => {
        loading.close();
        ElMessage({ message: '网络异常', type: 'error'});
      })
}

// 根据id获取配置数据
const getCardTypeSet = () => {
  _getCardTypeSet(props.id)
      .then(res => {
        console.log(res);
        if(res.data.ok) {
          let data = res.data.data||[];
          if(data.length > 0) {
            for (let i = 0; i < data.length; i++) {
              for (let j = 0; j < personTypeList.data.length; j++) {
                if(data[i].certId === personTypeList.data[j].id) {
                  selectPerson.data.push(personTypeList.data[j]);
                  selectData.data.push(data[i])
                }
              }
              for (let j = 0; j < carTypeList.data.length; j++) {
                if(data[i].certId === carTypeList.data[j].id) {
                  selectCar.data.push(carTypeList.data[j])
                  let userCertAreas = data[i]['certAreaVos'];
                  let arr = []
                  userCertAreas.forEach(v => {
                    arr.push(v.areaId)
                  })
                  selectCarData.data.push({ ... data[i], userCertAreas:arr})
                }
              }
            }
          }
        }
      })
      .catch(err => {
        console.log(err);
      })
}
</script>

<style scoped lang="scss">
.set-box{
 .set-box-item{
   padding-bottom: 30px;
   p{
     font-size: 18px;
     font-weight: bold;
     margin-bottom: 10px;
   }
   .item-type{
     display: flex;
     align-items: center;
     .item-type-label{
       margin-right: 10px;
     }
   }
   .item-number{
     display: flex;
     flex-wrap: wrap;
     .item-number-value{
       margin-right: 30px;

     }
   }
   .item-number-car{
     .item-number-label{
       font-weight: bold;
       margin-bottom: 10px;
       margin-top: 20px;
       font-size: 16px;
       display: inline-block;
     }
     .item-number-item{
       display: flex;
       align-items: center;
       span{
         display: inline-block;
         width: 80px;
       }
     }
   }
 }
}
</style>